#include <QList>

#include "world.h"
#include "collisionobject.h"

World::World(QDeclarativeItem *parent) :
    QDeclarativeItem(parent)
{
    m_audioOutput = new GE::AudioOut(&m_audioMixer, this);
}

World::~World()
{
    if (m_audioOutput != 0)
    {
        delete m_audioOutput;
        m_audioOutput = 0;
    }
}

GE::AudioBuffer *World::addAudio(QString source)
{
    GE::AudioBuffer *buffer = GE::AudioBuffer::loadWav(source);
    return buffer;
}

QVariant World::checkCollision(QDeclarativeItem *item, bool solid) const
{
    if (!item) return QVariant();

    QList<QGraphicsItem *> list = item->collidingItems();
    QList<QObject*> items;

    foreach (QGraphicsItem * gi, list)
    {
        CollisionObject *obj = qobject_cast<CollisionObject*>(gi);
        if (obj)
        {
            if (obj->solid() == solid)
            {
                QDeclarativeItem *collidedItem = qobject_cast<QDeclarativeItem*>(gi);
                if (collidedItem)
                    items << collidedItem;
            }
        }
    }

    return QVariant::fromValue(items);
}

QVariant World::checkObjectCollision(QDeclarativeItem *item) const
{
    return checkCollision(item, false);
}

QVariant World::checkGroundCollision(QDeclarativeItem *item) const
{
   return checkCollision(item, true);
}

QRect World::intersectedRect(QDeclarativeItem *item1, QDeclarativeItem *item2) const
{
    if (!(item1 && item2)) return QRect();

    QPainterPath p1 = item1->shape();
    QPainterPath p2 = item2->shape().translated(item2->pos() - item1->pos());
    QPainterPath intersection = p2.intersected(p1);

    const QRect bounds = intersection.boundingRect().toRect();

    return bounds;
}
